package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.admin.mapper.AdminMapper;
import com.itheima.admin.mapper.AdminRoleRelationMapper;
import com.itheima.admin.service.AdminManageService;
import com.itheima.model.admin.dtos.AdminCreateDto;
import com.itheima.model.admin.dtos.AdminQueryDto;
import com.itheima.model.admin.dtos.AdminUpdateDto;
import com.itheima.model.admin.pojos.Admin;
import com.itheima.model.admin.pojos.AdminRoleRelation;
import com.itheima.model.admin.vos.AdminDetailVo;
import com.itheima.model.common.dtos.PageResponseResult;
import com.itheima.model.common.dtos.ResponseResult;
import com.itheima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 管理员管理服务实现
 * 
 * @author itheima
 */
@Slf4j
@Service
public class AdminManageServiceImpl implements AdminManageService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleRelationMapper adminRoleRelationMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public ResponseResult listAdmins(AdminQueryDto dto) {
        // 构建分页对象
        IPage<Admin> page = new Page<>(dto.getPage(), dto.getSize());

        // 构建查询条件
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        
        // 用户名模糊查询
        if (dto.getUsername() != null && !dto.getUsername().trim().isEmpty()) {
            wrapper.like(Admin::getUsername, dto.getUsername());
        }
        
        // 昵称模糊查询
        if (dto.getNickname() != null && !dto.getNickname().trim().isEmpty()) {
            wrapper.like(Admin::getNickname, dto.getNickname());
        }
        
        // 状态精确查询
        if (dto.getStatus() != null) {
            wrapper.eq(Admin::getStatus, dto.getStatus());
        }
        
        // 按创建时间倒序
        wrapper.orderByDesc(Admin::getCreateTime);

        // 执行分页查询
        IPage<Admin> result = adminMapper.selectPage(page, wrapper);

        // 转换为VO，并查询角色信息
        List<AdminDetailVo> voList = new ArrayList<>();
        for (Admin admin : result.getRecords()) {
            AdminDetailVo vo = new AdminDetailVo();
            BeanUtils.copyProperties(admin, vo);
            
            // 转换Date为LocalDateTime
            if (admin.getLastLoginTime() != null) {
                vo.setLastLoginTime(LocalDateTime.ofInstant(
                    admin.getLastLoginTime().toInstant(), ZoneId.systemDefault()));
            }
            if (admin.getCreateTime() != null) {
                vo.setCreateTime(LocalDateTime.ofInstant(
                    admin.getCreateTime().toInstant(), ZoneId.systemDefault()));
            }
            if (admin.getUpdateTime() != null) {
                vo.setUpdateTime(LocalDateTime.ofInstant(
                    admin.getUpdateTime().toInstant(), ZoneId.systemDefault()));
            }
            
            // 查询角色
            List<String> roles = adminMapper.selectRolesByAdminId(admin.getId());
            vo.setRoles(roles);
            
            voList.add(vo);
        }

        PageResponseResult pageResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) result.getTotal());
        pageResult.setData(voList);
        return pageResult;
    }

    @Override
    public ResponseResult getAdminById(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 查询管理员详情（包含角色和权限）
        Admin admin = adminMapper.selectAdminWithRolesAndPermissions(id);
        if (admin == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "管理员不存在");
        }

        // 转换为VO
        AdminDetailVo vo = new AdminDetailVo();
        BeanUtils.copyProperties(admin, vo);
        
        // 查询角色和权限
        vo.setRoles(adminMapper.selectRolesByAdminId(id));
        vo.setPermissions(adminMapper.selectPermissionsByAdminId(id));

        return ResponseResult.okResult(vo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult createAdmin(AdminCreateDto dto) {
        // 参数校验
        if (dto.getUsername() == null || dto.getUsername().trim().isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名不能为空");
        }
        if (dto.getPassword() == null || dto.getPassword().trim().isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "密码不能为空");
        }

        // 检查用户名是否已存在
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername, dto.getUsername());
        int count = adminMapper.selectCount(wrapper).intValue();
        if (count > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "用户名已存在");
        }

        // 创建管理员
        Admin admin = new Admin();
        BeanUtils.copyProperties(dto, admin);
        
        // 加密密码
        admin.setPassword(passwordEncoder.encode(dto.getPassword()));
        admin.setCreateTime(new Date());
        admin.setUpdateTime(new Date());
        
        // 保存管理员
        int rows = adminMapper.insert(admin);
        if (rows == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "创建管理员失败");
        }

        // 分配角色
        if (dto.getRoleIds() != null && !dto.getRoleIds().isEmpty()) {
            assignRolesToAdmin(admin.getId(), dto.getRoleIds());
        }

        return ResponseResult.okResult(admin);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateAdmin(Integer id, AdminUpdateDto dto) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 检查管理员是否存在
        Admin existingAdmin = adminMapper.selectById(id);
        if (existingAdmin == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "管理员不存在");
        }

        // 更新管理员信息
        Admin admin = new Admin();
        admin.setId(id);
        BeanUtils.copyProperties(dto, admin);
        admin.setUpdateTime(new Date());

        int rows = adminMapper.updateById(admin);
        if (rows == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "更新管理员失败");
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteAdmin(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 不能删除超级管理员
        if (id == 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "不能删除超级管理员");
        }

        // 检查管理员是否存在
        Admin admin = adminMapper.selectById(id);
        if (admin == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "管理员不存在");
        }

        // 删除管理员
        int rows = adminMapper.deleteById(id);
        if (rows == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "删除管理员失败");
        }

        // 删除角色关联
        LambdaQueryWrapper<AdminRoleRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdminRoleRelation::getAdminId, id);
        adminRoleRelationMapper.delete(wrapper);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult toggleAdminStatus(Integer id, Integer status) {
        if (id == null || status == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 不能禁用超级管理员
        if (id == 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "不能禁用超级管理员");
        }

        // 检查管理员是否存在
        Admin admin = adminMapper.selectById(id);
        if (admin == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "管理员不存在");
        }

        // 更新状态
        admin.setStatus(status);
        admin.setUpdateTime(new Date());
        int rows = adminMapper.updateById(admin);
        if (rows == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "更新状态失败");
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult resetPassword(Integer id, String newPassword) {
        if (id == null || newPassword == null || newPassword.trim().isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 检查管理员是否存在
        Admin admin = adminMapper.selectById(id);
        if (admin == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "管理员不存在");
        }

        // 更新密码
        admin.setPassword(passwordEncoder.encode(newPassword));
        admin.setUpdateTime(new Date());
        int rows = adminMapper.updateById(admin);
        if (rows == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "重置密码失败");
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult assignRoles(Integer adminId, List<Integer> roleIds) {
        if (adminId == null || roleIds == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 检查管理员是否存在
        Admin admin = adminMapper.selectById(adminId);
        if (admin == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "管理员不存在");
        }

        // 删除旧的角色关联
        LambdaQueryWrapper<AdminRoleRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdminRoleRelation::getAdminId, adminId);
        adminRoleRelationMapper.delete(wrapper);

        // 添加新的角色关联
        if (!roleIds.isEmpty()) {
            assignRolesToAdmin(adminId, roleIds);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 为管理员分配角色（内部方法）
     */
    private void assignRolesToAdmin(Integer adminId, List<Integer> roleIds) {
        List<AdminRoleRelation> relations = roleIds.stream()
                .map(roleId -> {
                    AdminRoleRelation relation = new AdminRoleRelation();
                    relation.setAdminId(adminId);
                    relation.setRoleId(roleId);
                    return relation;
                })
                .collect(Collectors.toList());

        for (AdminRoleRelation relation : relations) {
            adminRoleRelationMapper.insert(relation);
        }
    }
}

